/***
 * Implementation of js-simple-storage interface for Cookies
 *
 * The idea here is to keep things simple and extend the window
 * object until there are explicit requirements;
 */

 (function(window, undefined) {
     var storage = window.storage || {};
     
     storage.cookie = {
         getItem: function(key) {
             key = new String(key).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
             var regex = new RegExp('(?:^|;)\\s?' + key + '=(.*?)(?:;|$)', 'i'),
             match = document.cookie.match(regex);
             return match && decodeURIComponent(match[1]);
         },
         setItem: function(key, value, days) {
             var expires = "; ";
             if (days) {
                 var date = new Date();
                 date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                 expires = '; expires=' + date.toGMTString();
             }

             document.cookie = key + '=' + value + expires + '; path=/';
         },
         removeItem: function(key) {
             this.setItem(key, '', -1);
             return;
         },
         clear: function() {
             var cookies = document.cookie.split(";");
             for (var i = 0; i < cookies.length; i++) {
                 var c = cookies[i],
                 eqp = c.indexOf("=");
                 var key = eqp > -1 ? c.substr(0, eqp) : c;
                 this.removeItem(key);
             }
         },
         keys: function() {
             var cookies = document.cookie.split(";");
             var keys_ = new Array();
             for (var i = 0; i < cookies.length; i++) {
                  var cookie = cookies[i],
                      k_ = cookie.indexOf("=");
                  var key = k_ > -1 ? cookie.substr(0, k_) : cookie;
                  keys_.push(key);
             }
             return keys_;
         }
     };

     /* set or update window storage object */
     window.storage = storage;
     window.storage.cookie = storage.cookie;
 })(window);
 